
package com.mengmeizi;

import com.mengmeizi.ui.PorterDuffView;
import com.mengmeizi.util.Const;
import com.mengmeizi.util.CustomDialog;
import com.mengmeizi.util.DialogUtil;
import com.mengmeizi.util.ImageManager;
import com.mengmeizi.util.Tools;
import com.umeng.analytics.MobclickAgent;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.FloatMath;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class ActImageDetail extends Activity implements Callback, OnClickListener, OnTouchListener, OnDismissListener {

    private SoftApplication application;

    private ImageView currentImageView;

    private boolean isManager = false;

    private Button btnDesktop, btnSave, btnDelete, btnShare;

    private Handler handler;

    private String currImageUrl;

    private File cropFile;

    Matrix matrix = new Matrix();

    Matrix savedMatrix = new Matrix();

    DisplayMetrics dm;

    float minScaleR;// 最小缩放比例

    static final float MAX_SCALE = 4f;// 最大缩放比例

    static final int NONE = 0;// 初始状态

    static final int DRAG = 1;// 拖动

    static final int ZOOM = 2;// 缩放

    int mode = NONE;

    PointF prev = new PointF();

    PointF mid = new PointF();

    float dist = 1f;

    private Bitmap bitmap;

    private CustomDialog saveImageSuccessDialog;

    private ImageManager imgManager;

    // /** true时不显示Dialog，只Toast提示；false时显示Dialog */
    // private static boolean isShowSaveDialog = false;

    // private LinearLayout content_layout, nowifi_layout, bottom_layout;

    private Button btnTryAgain;

    private Button btnNarrow;

    private Button btnEnlarge;

    private float rate = 1.0f;

    private boolean isShowDialog = false;

    private Matrix defaultMatrix = new Matrix();

    private SharedPreferences pre;

    private boolean isRemind = true;

    private boolean networkInvalible;

    private LayoutInflater inflater;

    private View contentView;

    private View wifiNotifyView;

    private LinearLayout contentLayout;

    private LinearLayout llyAd;

    public PorterDuffView loadingPorterDuffView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        contentLayout = new LinearLayout(this);

        setContentView(contentLayout);

        application = (SoftApplication) getApplication();
        application.addActivity(this);

        handler = new Handler(this);

        imgManager = ImageManager.getManger();

        Bundle bundle = getIntent().getExtras();
        isManager = bundle.getBoolean(Const.IS_MANAGER);
        currImageUrl = bundle.getString(Const.BUNDLE_IMAGEURL);

        pre = getSharedPreferences(Const.SHARED_PREFERENCES_MESSAGE, Context.MODE_PRIVATE);
        isRemind = pre.getBoolean(Const.SHARED_REMIND, true);

        inflater = (LayoutInflater) getLayoutInflater();

        initView();
    }

    private void initView() {

        contentView = inflater.inflate(R.layout.act_detail_lly, null);
        contentLayout.removeAllViews();
        contentLayout.addView(contentView);

        llyAd = (LinearLayout) contentView.findViewById(R.id.adLayout);

        currentImageView = (ImageView) contentView.findViewById(R.id.imvDetailImage);
        currentImageView.setVisibility(View.INVISIBLE);
        currentImageView.setOnTouchListener(this);

        loadingPorterDuffView = (PorterDuffView) contentView.findViewById(R.id.porterDuffView);

        btnDesktop = (Button) contentView.findViewById(R.id.btnDesktop);
        btnSave = (Button) contentView.findViewById(R.id.btnSave);
        btnDelete = (Button) contentView.findViewById(R.id.btnDelete);
        btnShare = (Button) contentView.findViewById(R.id.btnShare);
        btnDesktop.setOnClickListener(this);
        btnSave.setOnClickListener(this);
        btnDelete.setOnClickListener(this);
        btnShare.setOnClickListener(this);

        btnNarrow = (Button) contentView.findViewById(R.id.btnNarrow);
        btnNarrow.setOnClickListener(this);
        btnEnlarge = (Button) contentView.findViewById(R.id.btnEnlarge);
        btnEnlarge.setOnClickListener(this);

        if (isManager) { // 从管理页面进来
            btnSave.setVisibility(View.GONE);
            btnDelete.setVisibility(View.VISIBLE);
        } else {
            btnDelete.setVisibility(View.GONE);
            btnSave.setVisibility(View.VISIBLE);
        }

        if (isManager) {
            currImageUrl += "_big";
        }
    }

    /***
     * 获取图片到imageview
     */
    private void getImage() {
        if (currImageUrl != null && !"".equals(currImageUrl)) {
            // handler.sendEmptyMessage(Const.DIALOG_SHOW);
            imgManager.loadImage2ImageView(this, currImageUrl, currentImageView, Const.TYPE_BIG_IMAGE, handler);
        }
    }

    /***
     * 初始化图片
     */
    private void processImage() {
        dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);// 获取分辨率
        minZoom();
        center();
        currentImageView.setImageMatrix(matrix);
        currentImageView.setVisibility(View.VISIBLE);
    }

    @Override
    public void onClick(View v) {
        if (v instanceof Button) {
            if (v == btnDesktop) {
                handler.sendEmptyMessage(Const.DIALOG_SHOW);
                cropAndSetWallpaper();
                // 统计设置壁纸
                MobclickAgent.onEvent(ActImageDetail.this, "click_set_wallpaper",
                        currImageUrl.substring(currImageUrl.lastIndexOf("/")));
            } else if (v == btnSave) {
                handler.sendEmptyMessage(Const.DIALOG_SHOW);
                new Thread(saveImageRunnable).start();
                // 统计下载的图片
                MobclickAgent.onEvent(ActImageDetail.this, "click_download_wallpaper",
                        currImageUrl.substring(currImageUrl.lastIndexOf("/")));
            } else if (v == btnDelete) {
                delCurrentImages();
            } else if (v == btnShare) {
                showShareList();
                // 统计分享的图片
                MobclickAgent.onEvent(ActImageDetail.this, "click_share_wallpaper",
                        currImageUrl.substring(currImageUrl.lastIndexOf("/")));
            } else if (v == btnTryAgain) {
                getImage();
            } else if (v == btnNarrow) {
                if (rate >= 1.2) {
                    rate -= 0.2f;
                    matrix.set(defaultMatrix);
                    matrix.postScale(rate, rate);
                    center();
                    currentImageView.setImageMatrix(matrix);
                } else {
                    matrix.set(defaultMatrix);
                    center();
                    currentImageView.setImageMatrix(matrix);
                }
            } else if (v == btnEnlarge) {
                if (rate < 2.0f) {
                    rate += 0.2f;
                    matrix.set(defaultMatrix);
                    matrix.postScale(rate, rate);
                    center();
                    currentImageView.setImageMatrix(matrix);
                }
            }
        }
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        ProgressDialog dialog = new ProgressDialog(this);
        dialog.setOnDismissListener(this);
        // dialog.setIndeterminateDrawable(getResources().getDrawable(R.anim.refresh_round));
        dialog.setMessage(getString(R.string.loading));
        dialog.setIndeterminate(false);// 设置进度条是否为不明确（没有明确的数字来表示进度）
        return dialog;
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case Const.REFRESH_IMG:
                bitmap = (Bitmap) msg.obj;
                if (bitmap != null) {
                    loadingPorterDuffView.setVisibility(View.GONE);
                    if (networkInvalible) {
                        networkInvalible = false;
                        // 加载内容页面
                        contentLayout.removeAllViews();
                        contentLayout.addView(contentView);
                    }
                    processImage();
                }

                break;
            case Const.DIALOG_SHOW:
                showDialog(Const.DIALOG_ID);
                isShowDialog = true;
                break;
            case Const.DIALOG_DISMISS:
                if (isShowDialog) {
                    isShowDialog = false;
                    dismissDialog(Const.DIALOG_ID);
                }
                break;
            case Const.DIALOG_ID:
                handler.sendEmptyMessage(Const.DIALOG_DISMISS);
                Tools.showShortToast(ActImageDetail.this, getString(R.string.setWallpaperSuccess));
                break;
            case Const.IMAGE_SAVE_SUCCESS:
                handler.sendEmptyMessage(Const.DIALOG_DISMISS);
                showSaveSuccessDialog();
                break;
            case Const.DETAIL_SET_WALLPAPER:
                cropFile = new File(Environment.getExternalStorageDirectory(), "/temporary_holder.png");

                try {
                    handler.sendEmptyMessage(Const.DIALOG_DISMISS);
                    Intent intent = new Intent("com.android.camera.action.CROP");
                    intent.setDataAndType((Uri) msg.obj, "image/*");
                    intent.putExtra("crop", "true");
                    intent.putExtra("outputX", msg.arg1);
                    intent.putExtra("outputY", msg.arg2);
                    intent.putExtra("setWallpaper", true);
                    intent.putExtra("noFaceDetection", true);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cropFile));
                    intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.name());
                    startActivityForResult(intent, 100);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case Const.DIALOG_CONFIRM_BUTTON:
                remind();
                DialogUtil.dismissDialog(saveImageSuccessDialog);
                Tools.switchActivity(ActImageDetail.this, ActSwitchWallpaper.class, null);
                break;
            case Const.DIALOG_CANCEL_BUTTON:
                remind();
                DialogUtil.dismissDialog(saveImageSuccessDialog);
                break;
            case Const.SHOW_TOAST:
                handler.sendEmptyMessage(Const.DIALOG_DISMISS);
                Toast.makeText(ActImageDetail.this, getString(R.string.imageExist), Toast.LENGTH_SHORT).show();
                break;
            case Const.CHECK_NETWORK:
                if (!Tools.hasNetwork(this)) { // 网络正常
                    networkInvalible = true;
                    wifiNotifyView = inflater.inflate(R.layout.no_wifi_notify, null);
                    btnTryAgain = (Button) wifiNotifyView.findViewById(R.id.btnTryAgain);
                    btnTryAgain.setOnClickListener(this);
                    LayoutParams layoutParams = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
                    contentLayout.removeAllViews();
                    contentLayout.addView(wifiNotifyView, layoutParams);

                    handler.sendEmptyMessage(Const.DIALOG_DISMISS);
                }
                break;
            case Const.LOADING_PUBLISH:
                loadingPorterDuffView.setProgress((Float) msg.obj);
                break;
            case Const.LOADING_PUBLISH_FAST:
                new Runnable() {
                    float process = 0.0f;

                    public void run() {
                        try {
                            while (process <= 100.0f) {
                                Thread.sleep(10);
                                loadingPorterDuffView.setProgress(process);
                                process++;
                            }
                            loadingPorterDuffView.setVisibility(View.GONE);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }.run();
                break;
            default:
                break;
        }

        return false;
    }

    private void remind() {
        CheckBox checkBox = saveImageSuccessDialog.getCheckBox();
        boolean isCheck = checkBox.isChecked();
        if (isCheck) {
            isRemind = false;
            Editor editor = pre.edit();
            editor.putBoolean(Const.SHARED_REMIND, false);
            editor.commit();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 100:
                if (resultCode == Activity.RESULT_OK) {
                    FileInputStream fis = null;
                    BufferedInputStream bis = null;
                    try {
                        fis = new FileInputStream(cropFile);
                        bis = new BufferedInputStream(fis);
                        setWallpaper(bis);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            if (bis != null) {
                                bis.close();
                            }
                            if (fis != null) {
                                fis.close();
                            }
                            if (cropFile.exists()) {
                                cropFile.delete();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                break;

            default:
                break;
        }
    }

    private void showSaveSuccessDialog() {
        if (isRemind) {
            saveImageSuccessDialog = DialogUtil.showAlertDialog(this, handler, null, null, "",
                    getString(R.string.saveImageSuccessInfo), true, "", "", Const.DIALOG_CONFIRM_BUTTON,
                    Const.DIALOG_CANCEL_BUTTON);
        } else {
            Tools.showLongToast(this, getString(R.string.saveImageSuccess));
        }
    }

    /** 删除ViewFlipper当前显示的图片 */
    private void delCurrentImages() {
        String delString = null;
        if (isManager) {
            delString = currImageUrl.substring(0, currImageUrl.indexOf("_big"));
        } else {
            delString = currImageUrl;
        }
        File tmpFile = new File(delString);
        if (tmpFile.exists()) {
            tmpFile.delete();
            // 再次启动manager，传入新参数
            Intent intent = new Intent(this, ActManager.class);
            intent.putExtra("delete", false);
            startActivity(intent);
            this.finish();
        }
    }

    private Runnable saveImageRunnable = new Runnable() {

        @Override
        public void run() {

            File file = new File(Const.FILENAME_DOWNLOAD);
            if (!file.exists()) {
                file.mkdir();
            }
            if (currImageUrl != null && !"".equals(currImageUrl)) {
                int pos = currImageUrl.lastIndexOf(File.separator);
                String name = currImageUrl.substring(pos + 1, currImageUrl.length());
                BufferedOutputStream bos = null;
                try {
                    File saveFile = new File(Const.FILENAME_DOWNLOAD + name);
                    if (!saveFile.exists()) {
                        bos = new BufferedOutputStream(new FileOutputStream(saveFile));
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                        bos.flush();
                        handler.sendEmptyMessage(Const.IMAGE_SAVE_SUCCESS);
                    } else {
                        Message msg = new Message();
                        msg.obj = getString(R.string.imageExist);
                        msg.what = Const.SHOW_TOAST;
                        handler.sendMessage(msg);
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (bos != null) {
                            bos.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    };

    private LayoutParams layoutParams;

    private void showShareList() {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.share));
        startActivity(Intent.createChooser(intent, getTitle()));
    }

    protected void cropAndSetWallpaper() {

        new Thread() {

            @Override
            public void run() {
                super.run();
                if (Tools.hasSDCard()) {
                    Uri bitmapUri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, null,
                            null));
                    Message msg = new Message();
                    msg.obj = bitmapUri;
                    msg.arg1 = bitmap.getWidth();
                    msg.arg2 = bitmap.getHeight();
                    msg.what = Const.DETAIL_SET_WALLPAPER;
                    handler.sendMessage(msg);
                } else {
                    try {
                        setWallpaper(bitmap);
                        handler.sendEmptyMessage(Const.DIALOG_DISMISS);
                        Message msg = new Message();
                        msg.what = Const.SHOW_TOAST;
                        msg.obj = getString(R.string.setWallpaperSuccess);
                        handler.sendMessage(msg);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }.start();
    }

    /**
     * 触屏监听
     */
    public boolean onTouch(View v, MotionEvent event) {

        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            // 主点按下
            case MotionEvent.ACTION_DOWN:
                savedMatrix.set(matrix);
                prev.set(event.getX(), event.getY());
                mode = DRAG;
                break;
            // 副点按下
            case MotionEvent.ACTION_POINTER_DOWN:
                dist = spacing(event);
                // 如果连续两点距离大于10，则判定为多点模式
                if (spacing(event) > 10f) {
                    savedMatrix.set(matrix);
                    midPoint(mid, event);
                    mode = ZOOM;
                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_POINTER_UP:
                mode = NONE;
                break;
            case MotionEvent.ACTION_MOVE:
                if (mode == DRAG) {
                    matrix.set(savedMatrix);
                    matrix.postTranslate(event.getX() - prev.x, event.getY() - prev.y);
                } else if (mode == ZOOM) {
                    float newDist = spacing(event);
                    if (newDist > 10f) {
                        matrix.set(savedMatrix);
                        // float tScale = newDist / dist;
                        // matrix.postScale(tScale, tScale, mid.x, mid.y);
                        rate = newDist / dist;
                        matrix.postScale(rate, rate, mid.x, mid.y);
                    }
                }
                break;
        }
        currentImageView.setImageMatrix(matrix);
        CheckView();
        return true;
    }

    /**
     * 限制最大最小缩放比例，自动居中
     */
    private void CheckView() {
        float p[] = new float[9];
        matrix.getValues(p);
        if (mode == ZOOM) {
            if (p[0] < minScaleR) {
                rate = 1;
                matrix.setScale(minScaleR, minScaleR);
            }
            if (p[0] > MAX_SCALE) {
                matrix.set(savedMatrix);
            }
        }
        center();
    }

    /**
     * 最小缩放比例，最大为100%
     */
    private void minZoom() {
        minScaleR = Math.min((float) dm.widthPixels / (float) bitmap.getWidth(), (float) dm.heightPixels
                / (float) bitmap.getHeight());
        if (minScaleR < 1.0) {
            matrix.postScale(minScaleR, minScaleR);
            defaultMatrix.set(matrix);
        }
    }

    private void center() {
        center(true, true);
    }

    /**
     * 横向、纵向居中
     */
    protected void center(boolean horizontal, boolean vertical) {
        if (bitmap == null) {
            return;
        }

        Matrix m = new Matrix();
        m.set(matrix);
        RectF rect = new RectF(0, 0, bitmap.getWidth(), bitmap.getHeight());
        m.mapRect(rect);

        float height = rect.height();
        float width = rect.width();

        float deltaX = 0, deltaY = 0;

        if (vertical) {
            // 图片小于屏幕大小，则居中显示。大于屏幕，上方留空则往上移，下方留空则往下移
            int screenHeight = dm.heightPixels;
            if (height < screenHeight) {
                deltaY = (screenHeight - height) / 2 - rect.top;
            } else if (rect.top > 0) {
                deltaY = -rect.top;
            } else if (rect.bottom < screenHeight) {
                deltaY = currentImageView.getHeight() - rect.bottom;
            }
        }

        if (horizontal) {
            int screenWidth = dm.widthPixels;
            if (width < screenWidth) {
                deltaX = (screenWidth - width) / 2 - rect.left;
            } else if (rect.left > 0) {
                deltaX = -rect.left;
            } else if (rect.right < screenWidth) {
                deltaX = screenWidth - rect.right;
            }
        }
        matrix.postTranslate(deltaX, deltaY);
    }

    /**
     * 两点的距离
     */
    private float spacing(MotionEvent event) {
        float x = event.getX(0) - event.getX(1);
        float y = event.getY(0) - event.getY(1);
        return FloatMath.sqrt(x * x + y * y);
    }

    /**
     * 两点的中点
     */
    private void midPoint(PointF point, MotionEvent event) {
        float x = event.getX(0) + event.getX(1);
        float y = event.getY(0) + event.getY(1);
        point.set(x / 2, y / 2);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (bitmap == null) {
            getImage();
        }
        llyAd.removeAllViews();
        // 加载广告栏
        if (application.getAdLayout() != null) {
            if (layoutParams == null) {
                layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            }
            llyAd.addView(application.getAdLayout(), layoutParams);
        }
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        // 清除广告栏
        llyAd.removeAllViews();
        MobclickAgent.onPause(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isManager) {
                Intent intent = new Intent(this, ActManager.class);
                startActivity(intent);
            }
            this.finish();
            llyAd.removeAllViews();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        // TODO Auto-generated method stub
        if (!networkInvalible && bitmap == null) {
            this.finish();
        }
    }

    @Override
    protected void onDestroy() {
        isShowDialog = false;
        if (bitmap != null) {
            imgManager.removeBitmap(bitmap, currImageUrl);
        }
        llyAd.removeAllViews();
        super.onDestroy();
    }

}
